#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
# sys.path.append('/opt/work/caffe/python')
sys.path.insert(0, '.')

import random
import argparse
import os
import numpy as np
from collections import OrderedDict
import struct
import cv2
import math
from math import cos, sin
import re
from matplotlib import pyplot as plt

# SLEEP_TIME = 40
SLEEP_TIME = 1

enable_out = True
out_path = r'/rootfs/media/kasim/Data1/data/VideoCropFace/quality1.txt'
image_base_path = r'/rootfs/media/kasim/Data1/data/VideoCropFace'
quality_list_file = r'/rootfs/media/kasim/Data1/data/VideoCropFace/face_image_q{}-{}.txt'
# select_list_file = r'/rootfs/media/kasim/Data1/data/VideoCropFace/face_select/face_image_q{}-{}_filter_filter.txt'
select_list_file = r'/rootfs/media/kasim/Data1/data/VideoCropFace/test/face_image_q{}-{}_filter_filter_rec_ok.txt'
device_id_set = {
    # '150100414a54443452067fa1d4c56600',  #  64  94 68.09% 越秀星汇隽庭 6(幢/座) 3(单元) 货梯梯 A面
    # '150100414a5444345203bccb439eb500',  # 197 319 61.76% 天水湖 1(幢/座) 1(单元) 2梯 A面
    # '150100414a54443452064d2c43e43600',  #  91 172 52.91% 大信时尚家园二期 4(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452064d2743243600',  #  23  51 45.10% 天水湖 3(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452067fa6d45f6600',  #  74 169 43.79% 天水湖 4(幢/座) 1(单元) 1梯 A面
    # '150100414a5444345203bcd04287b500',  # 176 411 42.82% 越秀星汇隽庭 3(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452064d2742c43600',  # 159 376 42.29% 溢彩家园 2(幢/座) 1(单元) 2梯 A面
    # '150100414a54443452067fa1d4cd6600',  # 235 560 41.96% 越秀星汇隽庭 4(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452067fa6d4a36600',  # 107 255 41.96% 名雅学府 1(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452067fa6d4b06600',  #  52 130 40.00% 越秀星汇隽庭 5(幢/座) 1(单元) 1梯 A面

    '150100414a54443452067fa6d4556600',  # 104 529 19.66% 越秀星汇隽庭 7(幢/座) 1(单元) 1梯 A面
    '150100414a54443452067fa1d4096600',  #  76 391 19.44% 越秀星汇隽庭 4(幢/座) 1(单元) 2梯 A面
    '150100414a54443452064d27432e3600',  #  11  64 17.19% 大信时尚家园三期 12(幢/座) 1(单元) 1梯 A面
    '150100414a54443452064d2c43e13600',  #  33 198 16.67% 大信时尚家园二期 1(幢/座) 1(单元) 1梯 A面
    '150100414a5444345203bccb439fb500',  #  37 261 14.18% 越秀星汇隽庭 5(幢/座) 1(单元) 2梯 A面
    '150100414a54443452064d2c43ed3600',  #  70 496 14.11% 大信时尚家园三期 9(幢/座) 1(单元) 1梯 A面
    '150100414a54443452064d2742c73600',  #  52 370 14.05% 大信时尚家园二期 5(幢/座) 1(单元) 1梯 A面
    '150100414a54443452067fa6d45c6600',  #  51 399 12.78% 星光礼寓 7(幢/座) 1(单元) 1梯 A面

    # '150100414a54443452067fa6d4bc6600',   # 6 384 1.56% 星光礼寓 6(幢/座) 1(单元) 2梯 A面
    # '150100414a5444345203bcd0428cb500',   # 8 611 1.31% 溢彩家园 4(幢/座) 1(单元) 1梯 A面
    # '150100414a5444345203bcd04294b500',   # 6 518 1.16% 星光礼寓 7(幢/座) 1(单元) 2梯 A面
    # '150100414a54443452064d2743283600',   # 6 586 1.02% 溢彩家园 5(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452064d2743383600',   # 3 433 0.69% 名雅居 3(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452067fa6d4be6600',   # 3 495 0.61% 越秀星汇隽庭 3(幢/座) 1(单元) 2梯 A面
    # '150100414a54443452064d2742ca3600',   # 0   8 0.00% 天水湖 2(幢/座) 1(单元) 1梯 A面
    # '150100414a5444345203bcd04293b500',   # 0 222 0.00% 名雅居 1(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452067fa1d40a6600',   # 0 298 0.00% 名雅居 2(幢/座) 1(单元) 1梯 A面
    # '150100414a54443452067fa1d40e6600',   # 0 554 0.00% 越秀星汇隽庭 7(幢/座) 1(单元) 2梯 A面
    # '150100414a54443452067fa6d45b6600',   # 0 677 0.00% 溢彩家园 3(幢/座) 1(单元) 1梯 A面
}


def draw_hist(plt, name, xlist, bins):
    if isinstance(xlist, np.ndarray):
        x = xlist
    else:
        x = np.array(xlist)
    n, bins, patches = plt.hist(x, bins, align=u'mid', facecolor='blue', alpha=0.5)
    plt.title('{}: {:.2f} {:.3f} {:.2f} {:.2f}'.format(name, x.mean(), x.std(), x.min(), x.max()))


def show_hist(value_list, min_value=0.0, max_value=1.0, dbin=0.1, dxticks=0.1, title_str='Age'):
    bins = np.linspace(min_value, max_value, int((max_value - min_value) / dbin) + 1)
    xticks = np.linspace(min_value, max_value, int((max_value - min_value) / dxticks) + 1)

    fig = plt.figure(title_str, figsize=(24, 12))
    plt.subplot(111)
    draw_hist(plt, title_str, value_list, bins)
    plt.xticks(xticks)
    plt.tight_layout()
    plt.show()


def show_hist_ex(value_list, bin_count=20, scale=1.0, min_value=None, max_value=None, title_str='Quality', mode=0):
    if isinstance(value_list, np.ndarray):
        values = value_list
    else:
        values = np.array(value_list)
    if scale != 1.0:
        values = values * scale
    if min_value is None:
        min_value = values.min()
        min_value = math.floor(min_value)
    if max_value is None:
        max_value = values.max()
        max_value = math.ceil(max_value)

    diff_value = max_value - min_value
    if mode != 0:
        if bin_count > diff_value:
            bin_count = diff_value
    dxticks = diff_value / bin_count

    show_hist(values, min_value, max_value, dxticks, dxticks, title_str)


def main():
    quality_interval = 5
    scale = 100
    bin_count = scale // quality_interval
    qualitys = []
    file_name_list = []

    # select_file_set = set()
    # for quality_index in range(bin_count):
    #     quality_start = quality_index * quality_interval
    #     quality_end = quality_start + quality_interval
    #     select_list_file_path = select_list_file.format(quality_start, quality_end)
    #     with open(select_list_file_path, 'r') as file:
    #         for line in file.readlines():
    #             file_name = line.split()[0].strip()
    #             select_file_set.add(file_name)
    # for quality_index in range(bin_count):
    #     quality_start = quality_index * quality_interval
    #     quality_end = quality_start + quality_interval
    #     quality_list_file_path = quality_list_file.format(quality_start, quality_end)
    #     with open(quality_list_file_path, 'r') as file:
    #         for line in file.readlines():
    #             lines = line.split()
    #             file_name = lines[0].strip()
    #             device_id = file_name.split('/')[-4]
    #             if device_id not in device_id_set:
    #                 continue
    #             if file_name not in select_file_set:
    #                 continue
    #             quality = float(lines[-1].strip())
    #             qualitys.append(quality)
    #             file_name_list.append(file_name)

    for quality_index in range(bin_count):
        quality_start = quality_index * quality_interval
        quality_end = quality_start + quality_interval
        quality_list_file_path = quality_list_file.format(quality_start, quality_end)
        select_list_file_path = select_list_file.format(quality_start, quality_end)
        select_file_set = set()
        with open(select_list_file_path, 'r') as file:
            for line in file.readlines():
                file_name = line.split()[0].strip()
                select_file_set.add(file_name)

        with open(quality_list_file_path, 'r') as file:
            for line in file.readlines():
                lines = line.split()
                file_name = lines[0].strip()
                device_id = file_name.split('/')[-4]
                if device_id not in device_id_set:
                    continue
                if file_name not in select_file_set:
                    continue
                quality = float(lines[-1].strip())
                qualitys.append(quality)
                file_name_list.append(file_name)

    if enable_out:
        file_name_list.sort()
        with open(out_path, 'w') as file:
            for file_name in file_name_list:
                file.write(file_name + '\n')
        os.system('chmod a+wr {}'.format(out_path))

    if len(qualitys) > 0:
        show_hist_ex(qualitys, bin_count=bin_count, scale=scale, min_value=0, max_value=scale, title_str='Quality', mode=0)
    print('Finish!')


if __name__ == '__main__':
    main()
